﻿/**
 * @file applanguagecontroller.cpp
 * @author huangxb
 * @email 18228033207@163.com
 * @date 2024.04.04
 * @license MIT License
 * @brief 多语种管理类.
 *
 * @htmlonly
 * <span style="font-weight: bold">History</span>
 * @endhtmlonly
 * Version|Auther|Date|Describe
 * ------|----|------|--------
 * V1.0|huangxb|2024.04.04|创建
 */

/* 自定义头文件 */
#include "applanguagecontroller.h"
#include "logger.h"
/* 库头文件 */
#include <QTranslator>
#include <QCoreApplication>
#include <QFileInfo>
#include <QDir>

static const char* QM_FILE_ZH_CN = ".\\qt-custom-components_zh_CN.qm";
static const char* QM_FILE_EN_US = ".\\qt-custom-components_en_US.qm";

CAppLanguageController::CAppLanguageController(QObject *parent)
    : QObject(parent)
    , m_pCurTranslator(new QTranslator(this))
{

}

CAppLanguageController::~CAppLanguageController()
{

}

bool CAppLanguageController::ChangeLanguage(EAppLanguage nLang)
{
    QString strQMFile;
    switch(nLang) {
    case EAL_EN_US: strQMFile = QM_FILE_EN_US; break;
    case EAL_ZH_CN: strQMFile = QM_FILE_ZH_CN; break;
    default: Q_ASSERT(false); return false;
    }

    QDir dir(QCoreApplication::applicationDirPath());
    auto strFilePath = dir.absoluteFilePath(strQMFile);

    return ChangeLanguage(nLang, strFilePath);
}

bool CAppLanguageController::ChangeLanguage(EAppLanguage nLang, const QString &filePath)
{
    QString strQMFile = filePath;
    switch(nLang) {
    case EAL_EN_US: break;
    case EAL_ZH_CN: break;
    default: Q_ASSERT(false); return false;
    }

    if(m_nCurLanguage != EAL_UNKNOWN)
    {
        qApp->removeTranslator(m_pCurTranslator);
    }

    QFileInfo fi(strQMFile);
    QString strFile = fi.fileName();
    QString strDir = fi.dir().absolutePath();

    if(!m_pCurTranslator->load(strFile, strDir))
    {
        return false;
    }
    if(!qApp->installTranslator(m_pCurTranslator))
    {
        return false;
    }

    m_nCurLanguage = nLang;

    emit LanguageChanged();

    return true;
}

EAppLanguage CAppLanguageController::GetAppLanguage() const
{
    return m_nCurLanguage;
}

bool CAppLanguageController::IsChinese() const
{
    return m_nCurLanguage == EAL_ZH_CN;
}
